from django.shortcuts import render, HttpResponse, redirect
from app01.forms.project import ProjectForm
from django.http import JsonResponse
from app01 import models
def project(request):
    if request.method == 'GET':
        '''
        1. 从数据库中获取两部分数据
             我创建的所有项目: 已星标  未星标
             我参与的所有项目: 已星标  未星标
        2. 提取已星标
             列表 = 循环 [我创建的所有项目]+[我参与的所有项目] 把已星标的数据提取
        得到三个列表: 星标  创建  参与
       '''
        project_dict = {'star': [], 'my': [], 'join': []}
        my_project_list = models.Project.objects.filter(creator=request.tracer.user)
        for item in my_project_list:
            if item.star:
                project_dict['star'].append({'value': item, 'type': 'my'})
            else:
                project_dict['my'].append(item)
        join_project_list = models.ProjectUser.objects.filter(user=request.tracer.user)
        for item in join_project_list:
            if item.star:
                project_dict['star'].append({'value': item.project, 'type': 'join'})
            else:
                project_dict['join'].append(item.project)
        obj = ProjectForm(request)
        return render(request, 'project.html', {'obj': obj, 'project_dict': project_dict})
    obj = ProjectForm(request, request.POST)
    if obj.is_valid():
        obj.cleaned_data['creator'] = request.tracer.user
        models.Project.objects.create(**obj.cleaned_data)
        return JsonResponse({'status': True})
    return JsonResponse({'status': False, 'error': obj.errors})

def project_star(request, project_type, project_id):
    # if project_type == 'my':
    #     models.Project.objects.filter(id=project_id, creator=request.tracer.user).update(star=True)
    #     return redirect('app01:project')
    # if project_type == 'join':
    #     models.ProjectUser.objects.filter(project_id=project_id, user=request.tracer.user).update(star=True)
    #     return redirect('app01:project')
    # return HttpResponse('类型错误')
    ''' Ajax请求 '''
    if project_type == 'my':
        models.Project.objects.filter(id=project_id, creator=request.tracer.user).update(star=True)
        return JsonResponse({'result': 2})
    if project_type == 'join':
        models.ProjectUser.objects.filter(project_id=project_id, user=request.tracer.user).update(star=True)
        return JsonResponse({'result': 2})
    return HttpResponse('类型错误')


def project_unstar(request, project_type, project_id):
    if project_type == 'my':
        models.Project.objects.filter(id=project_id, creator=request.tracer.user).update(star=False)
        return JsonResponse({'result': 'my'})
    if project_type == 'join':
        models.ProjectUser.objects.filter(project_id=project_id, user=request.tracer.user).update(star=False)
        return JsonResponse({'result': 'join'})
    return HttpResponse('类型错误')
